package com.boyadegroot.divelog.ui.diver;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.boyadegroot.divelog.R;
import com.boyadegroot.divelog.data.DiveLogData;

public class DiverNew extends ActionBarActivity {

    public static final String IN_DIVERID = "previousDiverId";
    public static final String OUT_DIVERID = "diverId";

    private static final String TAG = DiverNew.class.getName();

    private long mPreviousDiverId;
    
    private EditText mUsername;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Log.v(TAG, "onCreate(Bundle savedInstanceState)");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_diver_new);
        getViewElements();
        Intent intent = getIntent();
        mPreviousDiverId = intent.getLongExtra(IN_DIVERID, -1);
        createView();
    }

    @Override
    public void onBackPressed() {
        // Log.v(TAG, "onBackPressed()");
        Intent intentData = new Intent();
        // Log.d(TAG, "Navigating back to diver with id = " + mPreviousDiverId);
        intentData.putExtra(OUT_DIVERID, mPreviousDiverId);
        setResult(Activity.RESULT_CANCELED, intentData);
        super.onBackPressed();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // TODO: Go back to the previous diver when pressing the action bar's Up/Home button
            case android.R.id.home:
                // Log.v(TAG, "Up/Home was pressed");
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_divernew, menu);
        MenuItem save = menu.findItem(R.id.menuitem_save);
        boolean mandatoryEmpty = (
            mUsername.getText().toString().trim().equals("")
        );
        save.setEnabled(!mandatoryEmpty);
        return true;
    }
    
    private final TextWatcher fieldsWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            updateSaveButton();
        }
    };
    
    private void updateSaveButton() {
        invalidateOptionsMenu();
    }

    public void onSaveNewDiverClick(MenuItem item) {
        // Log.v(TAG, "onSaveNewDiverClick(MenuItem item)");
        saveNewDiver();
    }

    private void saveNewDiver() {
        // Log.v(TAG, "saveNewDiver()");
        Context context = getApplicationContext();
        DiveLogData data = DiveLogData.getInstance(context);
        String username = mUsername.getText().toString();
        Toast toast = null;
        try {
            long mDiverId = data.addDiver(username, null, null, null, null);
            if (mDiverId != -1) {
                // Log.d(TAG, "Diver with id = " + mDiverId + " created successfully");
                Intent intentData = new Intent();
                intentData.putExtra(OUT_DIVERID, mDiverId);
                setResult(Activity.RESULT_OK, intentData);
                finish();
            } else {
                Log.e(TAG, "Error creating diver with username = " + username);
                toast = Toast.makeText(context, R.string.error_newdiver_create, Toast.LENGTH_SHORT);
            }
        } catch (SQLiteConstraintException e) {
            // Log.d(TAG, "SQLiteConstraintException creating diver with username = " + username + ": " + e.getMessage());
            if (data.diverExists(username)) {
                // Log.d(TAG, "A diver with username " + username + " already exists");
                mUsername.selectAll();
                toast = Toast.makeText(context, R.string.error_username_existing, Toast.LENGTH_SHORT);
            } else {
                toast = Toast.makeText(context, R.string.error_newdiver_create, Toast.LENGTH_SHORT);
            }
        } catch (SQLException e) {
            Log.e(TAG, "SQLException creating diver with username = " + username + ": " + e.getMessage());
            toast = Toast.makeText(context, R.string.error_newdiver_create, Toast.LENGTH_SHORT);
        }
        if (toast != null) {
            toast.setGravity(Gravity.TOP, 0, 150);
            toast.show();
        }
    }

    private void createView() {
        // Log.v(TAG, "createView()");
    }

    private void getViewElements() {
        // Log.v(TAG, "getViewElements()");
        mUsername = (EditText) findViewById(R.id.username);
        mUsername.addTextChangedListener(fieldsWatcher);
        mUsername.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Log.v(TAG, "onEditorAction(TextView v, int actionId, KeyEvent event)");
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // Log.v(TAG, "actionId == EditorInfo.IME_ACTION_DONE");
                    saveNewDiver();
                    return true;
                }
                return false;
            }
        });
    }

}